package com.tuju.jetpackfirstdemo.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DebugUtil {
    private static boolean DEBUG = true;
    private static final String TAG = "DebugUtil";
    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/ABaizeLog/";
    private static String DIR = "";
    private static final String FILE_NAME = "log";
    private static final String FILE_NAME_SUFFIX = ".txt";

    public static void printLogToSDCard(Context context, String message) {
        //如果SD卡不存在或无法使用，则无法把异常信息写入SD卡
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.w(TAG, "sdcard unmounted, skip dump exception");
                return;
            }
        }

        if (DIR.isEmpty()) {
            DIR = context.getPackageName() + "/";
        }

        File dir = new File(PATH + DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long current = System.currentTimeMillis();
        String dayTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(current));
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        File file = new File(PATH + FILE_NAME + dayTime + FILE_NAME_SUFFIX);
        boolean isFirst = file.exists();

        try {
            FileWriter fw = new FileWriter(file, true);
            PrintWriter pw = new PrintWriter(new BufferedWriter(fw));
            if (!isFirst) {
                dumpPhoneInfo(context, pw);
            }
            pw.println();
//            pw.println(time);
            pw.println(message);
            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump crash info failed");
        }
    }

    private static void dumpPhoneInfo(Context context, PrintWriter pw) throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                PackageManager.GET_ACTIVITIES);
        pw.print("App Version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);

        //Android版本号
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        //手机制造商
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        //手机型号
        pw.print("Model: ");
        pw.println(Build.MODEL);
        //CPU架构
        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

}
